﻿using System;
using Apps.Models;
using System.Collections.Generic;
using System.Linq;
using Apps.IDAL;
using Apps.IDAL.Sys;

namespace Apps.DAL.Sys
{
    public class SysRightGetRoleRightRepository : ISysRightGetRoleRightRepository, IDisposable
    {
         DBContainer db;
         public SysRightGetRoleRightRepository(DBContainer context)
        {
            this.db = context;
        }

        public DBContainer Context
        {
            get { return db; }
        }
        public List<P_Sys_GetRightByRole_Result> GetList(string roleId)
        {
            return Context.Database.SqlQuery<P_Sys_GetRightByRole_Result>(
                    string.Format(@"with MenuTree as (
  SELECT id, a.islast, substr(sys_connect_by_path(a.name, '>>'), 3) menupath, substr(sys_connect_by_path(a.sort, '-'), 0) sort
   FROM SysModule a
  START WITH a.parentid = '000'
  CONNECT BY a.parentid = PRIOR a.id)" +
  "select id moduleId,sort,replace(menupath, '>>', '<a class=\"fa fa-angle-double-right\" />') moduleName,replace(replace(replace(RightOperate, ',', ''), '$1', '<a class=\"fa fa-check-square-o color-green\"/>'), '$0', '<a class=\"fa fa-square-o color-red\"/>') keyCode" +
 @" from(
  select tMenuTree.id, tMenuTree.sort, tMenuTree.menupath, strcat(to_char(decode(instr(tRight.OperateKeyCodes, tMenuOperate.Keycode), 0, '$0', '$1') || tMenuOperate.name)) RightOperate
  from MenuTree tMenuTree
  join sysmoduleoperate tMenuOperate on tMenuTree.id = tMenuOperate.Moduleid
  join (
    select a.ModuleId, strcat(p.keycode) OperateKeyCodes
    from SysRight a join SYSRIGHTOPERATE p  on a.id = p.rightid
    where RoleId = '{0}'
    and ModuleId <> '0' and RIGHTFLAG = 1
    group by a.ModuleId
  ) tRight on tMenuTree.id = tRight.ModuleId
  where islast = 1
  group by tMenuTree.id,tMenuTree.menupath,tMenuTree.sort
  order by tMenuOperate.Sort  )
  order by sort", roleId)
                ).ToList();
        }

        public void Dispose()
        { }
    }

}
